import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn'
// const instance = getCurrentInstance()!

export const folderStyle = {
  receive: { icon: 'tabler:folder-down' },
  draft: { icon: 'akar-icons:draft' },
  send: { icon: 'tabler:folder-up' },
  delete: { icon: 'tabler:trash' },
  junk: { icon: 'hugeicons:remove-circle' },
  label: { icon: 'streamline:interface-bookmark-bookmarks-tags-favorite' },
  other: { icon: 'ic:outline-folder' }
}

export const mailClass = {
  top: '置顶邮件', // 置顶
  today: '今天', // 今天
  yesterday: '昨天', // 昨天
  friday: '本周五', // 本周五
  thursday: ' 本周四', // 本周四
  wednesday: '本周三', // 本周三
  tuesday: '本周二', // 本周二
  monday: '本周一', // 本周一
  lastWeek: '上周', // 上周
  twoWeek: '两周前', // 两周前
  threeWeek: '三周前', // 三周前
  earlierMonth: '本月更早', // 本月更早
  lastMonth: '上个月' // 上个月
}

export function getReplyContent(srcMailInfo) {
  let froms = ''
  srcMailInfo.froms.forEach((from) => {
    if (from.name != '') froms += from.name + ' &lt;'
    if (from.address != '') froms += from.address + '&gt;'
  })
  let receivers = ''
  srcMailInfo.receivers.forEach((receiver) => {
    if (receiver.name != '') receivers += receiver.name + ' &lt;'
    if (receiver.address != '') receivers += receiver.address + '&gt;'
  })
  let content =
    '<section>' +
    '<section>' +
    '	<hr />' +
    '<div id="" style="font: 13px/19px Arial; padding: 8px; background: #efefef; margin: 0;">' +
    '<div style="margin: 0;">' +
    '<strong>' +
    'From:' +
    '</strong>' +
    froms +
    '</div>' +
    '<div style="margin: 0;">' +
    '	<strong>' +
    '	Date:' +
    '</strong>' +
    srcMailInfo.sendTime +
    '</div>' +
    '<div style="margin: 0;">' +
    '<strong>' +
    'To:' +
    '</strong>' +
    receivers +
    '</div>' +
    '<div style="margin: 0;">' +
    '<strong>' +
    'Subject:' +
    '</strong>' +
    srcMailInfo.subject +
    '</div>' +
    '</div>' +
    '</section>' +
    '</section>'
  content = content += ' '
  return content
}

export function formatBytes(bytes) {
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  if (bytes === 0) return '0 B'

  const i = Math.floor(Math.log(bytes) / Math.log(1024))
  const converted = (bytes / Math.pow(1024, i)).toFixed(2) // 保留两位小数

  return `${converted} ${sizes[i]}`
}

export function convertMailClass(mailTime) {
  if (mailClass[mailTime] != undefined) return mailClass[mailTime]
  else {
    return dayjs(mailTime).format('YYYY年MM月')
  }
}

export function convertMailInfoShowTime(sendTime) {
  dayjs.locale('zh-cn')
  if (sendTime == undefined) return ''
  return dayjs(sendTime).format('YYYY年MM月DD日 (dddd) HH:mm')
}

export function calcMailTimeType(sendTime) {
  // 获取当前日期
  const currentDate = dayjs()
  const dateToCheck = dayjs(sendTime)

  // 获取上个月的1号
  const lastMonthFirstDay = currentDate.startOf('month').subtract(1, 'month')
  if (dateToCheck.isBefore(lastMonthFirstDay, 'day')) return dateToCheck.format('YYYYMM')

  // 获取本月1号
  const thisMonthFirstDay = currentDate.startOf('month')
  if (dateToCheck.isBefore(thisMonthFirstDay, 'day')) return 'lastMonth'

  // 获取三周前周一的日期
  const lastThreeWeek = currentDate.startOf('week').subtract(3, 'week')
  if (dateToCheck.isBefore(lastThreeWeek, 'day')) return 'earlierMonth'

  // 获取两周前周一的日期
  const lastTwoWeek = currentDate.startOf('week').subtract(2, 'week')
  if (dateToCheck.isBefore(lastTwoWeek, 'day')) return 'threeWeek'

  // 获取上周周一的日期
  const lastWeek = currentDate.startOf('week').subtract(1, 'week')
  if (dateToCheck.isBefore(lastWeek, 'day')) return 'twoWeek'

  const currentWeek = currentDate.startOf('week')
  if (dateToCheck.isBefore(currentWeek, 'day')) return 'lastWeek'

  if (dateToCheck.isSame(currentDate, 'day')) return 'today'

  const yesterday = currentDate.startOf('day').subtract(1, 'day')
  if (dateToCheck.isSame(yesterday, 'day')) return 'yesterday'

  const dayOfWeek = dateToCheck.day()
  if (dayOfWeek == 1) return 'monday'
  if (dayOfWeek == 2) return 'tuesday'
  if (dayOfWeek == 3) return 'wednesday'
  if (dayOfWeek == 4) return 'thursday'
  if (dayOfWeek == 5) return 'fridays'

  return 'error'
}

/**
 * 转换时间的显示格式。
 * 如果是今年的日期则简化为 "MM-DD HH:mm:ss" 格式，
 * 否则返回原格式 "YYYY-MM-DD HH:mm:ss"。
 * @param {string} sendTime - 发送时间字符串
 * @returns {string} - 转换后的发送时间字符串
 */
export function convertShowTime(sendTime: string): string {
  const currentTime = dayjs() // 获取当前时间
  const parsedTime = dayjs(sendTime) // 解析输入的时间

  if (parsedTime.year() === currentTime.year()) {
    return parsedTime.format('MM/DD HH:mm:ss')
  } else {
    return parsedTime.format('YYYY/MM/DD HH:mm:ss')
  }
}

function getActualLength(str) {
  let length = 0
  for (let i = 0; i < str.length; i++) {
    if (/[\u0000-\u00ff]/.test(str[i])) {
      length += 1 // 英文字符
    } else {
      length += 2 // 中文字符
    }
  }
  return length
}

function getFileExtension(filename) {
  return filename.slice(((filename.lastIndexOf('.') - 1) >>> 0) + 2)
}

export function truncateFileName(filename, maxLength = 19) {
  const extension = getFileExtension(filename).toLowerCase()
  const nameWithoutExtension = filename.slice(0, filename.lastIndexOf('.'))
  const actualMaxLength = maxLength - extension.length - 3 // 减去后缀名长度和省略号长度

  if (getActualLength(nameWithoutExtension) <= actualMaxLength) {
    return filename
  }

  let truncatedName = ''
  let currentLength = 0

  for (let i = 0; i < nameWithoutExtension.length; i++) {
    if (/[\u0000-\u00ff]/.test(nameWithoutExtension[i])) {
      currentLength += 1 // 英文字符
    } else {
      currentLength += 2 // 中文字符
    }

    if (currentLength > actualMaxLength) {
      break
    }
    truncatedName += nameWithoutExtension[i]
  }

  return `${truncatedName}...${extension}`
}

export function convertFileIcon(fileName) {
  if (fileName.indexOf('.') >= 0) {
    const fileType = fileName.substring(fileName.lastIndexOf('.') + 1).toLocaleLowerCase()
    // excel
    if (['xls', 'xlsx', 'xlsm', 'xlsb', 'sltx', 'xltm', 'xlam', 'csv'].includes(fileType)) {
      return 'vscode-icons:file-type-excel2'
    }
    // word
    if (['docx', 'doc', 'dotx', 'dotm'].includes(fileType)) {
      return 'vscode-icons:file-type-word2'
    }
    // ppt
    if (['pptx', 'ppt', 'pptm', 'potx', 'potm', 'ppsx', 'ppsm'].includes(fileType)) {
      return 'vscode-icons:file-type-powerpoint2'
    }
    // outlook
    if (['pst', 'ost', 'msg', 'eml'].includes(fileType)) {
      return 'vscode-icons:file-type-outlook'
    }
    // access
    if (['accdb', 'mdb', 'accde', 'mde'].includes(fileType)) {
      return 'vscode-icons:file-type-access2'
    }
    // 压缩包
    if (['rar', 'zip', '7z'].includes(fileType)) {
      return 'vscode-icons:file-type-zip'
    }
    // pdf
    if (['pdf'].includes(fileType)) {
      return 'vscode-icons:file-type-pdf2'
    }
    // text
    if (['txt', 'rtf'].includes(fileType)) {
      return 'vscode-icons:file-type-text'
    }
    // markdown
    if (['md'].includes(fileType)) {
      return 'vscode-icons:file-type-markdown'
    }
    // video
    if (
      [
        'mp4',
        'avi',
        'mov‌',
        'wmv‌',
        'mkv‌',
        'flv‌',
        'm4v‌',
        'mpeg‌',
        'mpg‌',
        'rmvb‌',
        'vob‌'
      ].includes(fileType)
    ) {
      return 'vscode-icons:file-type-video'
    }
    // audio
    if (
      ['wma', 'wav', 'mp3', 'aiff', 'cd', 'au', 'ape', 'aac', 'midi', 'vqf', 'ra'].includes(
        fileType
      )
    ) {
      return 'vscode-icons:file-type-audio'
    }
    // image
    if (['bmp', 'gif', 'jpg', 'pic', 'png', 'tif'].includes(fileType)) {
      return 'vscode-icons:file-type-image'
    }
  }
  return 'vscode-icons:default-file'
}
